package cn.sc.summer.mybatis.config.transaction;

import cn.hutool.extra.spring.SpringUtil;
import cn.sc.summer.mybatis.context.DynamicDataSourceContext;
import cn.sc.summer.constant.mybatisplus.datasource.DataSourceConstant;
import cn.sc.summer.constant.mybatisplus.TransManagerConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 类名：全局事务管理器
 *
 * @author a-xin
 * @date 2024/7/11 11:28
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "seata", name = "enabled", havingValue = "true")
public class SeataTransactionManagerConfig {

    /**
     * 配置@Transactional注解事务
     */
    @Bean(name = TransManagerConstant.SEATA)
    @ConditionalOnBean(name = DataSourceConstant.DYNAMIC_DATA_SOURCE)
    public PlatformTransactionManager transactionManager() {
        DynamicDataSourceContext dynamicDataSourceContext = SpringUtil.getBean(DataSourceConstant.DYNAMIC_DATA_SOURCE, DynamicDataSourceContext.class);
        log.info("==> Start initialization the TransactionManager: " + TransManagerConstant.SEATA);
        return new DataSourceTransactionManager(dynamicDataSourceContext);
    }

}
